package com.example.demo.controller.database;

import com.example.demo.pojo.vo.DataBaseAdd;
import com.example.demo.pojo.vo.QuerySql;
import com.example.demo.service.database.IDatabaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.SQLException;
import java.util.List;

@Controller
public class DatabaseController {
    @Autowired
    private IDatabaseService databaseService;

    @GetMapping("/databases")
    public String getAllDatabases(Model model) throws Exception {
        model.addAttribute("databases", databaseService.getAllDatabases());
        return "databases";
    }
    @PostMapping("/addDatabases")
    public String createDatabase(DataBaseAdd dataBaseAdd, Model model) throws Exception {
        System.out.println(dataBaseAdd+"sdsddf");
        try {
            String database = databaseService.createDatabase(dataBaseAdd);
        } catch (Exception e) {
            model.addAttribute("message", e.getMessage());
            throw new RuntimeException(e);
        }
        //重定向到databases页面
        String url = "redirect:/databases";
        return url;
    }

    /*打开添加页面*/
    @RequestMapping("/add")
    public String addDatabase(){
        return "adddatabase";
    }
    /*打开执行sql语句界面*/
    @GetMapping("/querySql")
    public String querySqlPage(@RequestParam(name = "databaseName", required = false) String databaseName,Model model) throws SQLException {
        List<String> allTables = databaseService.getAllTables(databaseName);
        model.addAttribute("databaseNameQuery", databaseName);
        model.addAttribute("allTables", allTables);
        return "query";
    }


    /*执行sql语句*/
    @PostMapping("/query")
    public String query(QuerySql querySql, Model model) throws Exception {
        try {
            databaseService.querySql(querySql);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //刷新当前页面
        return "redirect:/querySql?databaseName=" + querySql.getDatabaseName();
    }

}
